/*
 * @Author: tcosfish
 * @Date: 2022-08-19 11:56:43
 * @LastEditors: tcosfish
 * @LastEditTime: 2022-08-19 15:15:18
 * @FilePath: \loadFile\src\excel\feat\fillTemplateByRecord.ts
 */

import ry_database from "@/database/RyDataBase"
import RecordView from "@/database/views/Record.view"
import { In } from "typeorm"
import RyExcel from "../RyExcel"
import { templatePath } from "./create_month_report.temp"

async function fillTemplateByRecord(
  templateName: string,
  indexCol: number,
  fillCol: number,
  saveFilePath: string
) {
  // 1. 将模板复制到工作簿中
  await RyExcel.createTemplate()
    .addSheet(`1. ${templateName}`)
    .copy(templatePath(`${templateName}模板`), "Sheet1", 1)

  // 2. 获取当前模板中的指定代码行
  // TODO 太多冗余的命名
  const Sht = RyExcel.getCurrentSht()
  const dobCol = Sht?.getColumn(indexCol)
  const depsCode = dobCol!.values

  // 2.5 对部分行进行处理, 即(6001.001, 2221.01.02) 这种情况
  const goodCode = depsCode
    .map((dep) => {
      if (typeof dep === "string") {
        return dep.split(",")
      } else {
        return dep
      }
    })
    .flat()

  // 3. 拼接索引查询数据
  // TODO 实体被固定了, 不具备复用性
  const connection = await ry_database.init()
  const result = await connection
    .getInstance()
    .getRepository(RecordView)
    .createQueryBuilder("record_view")
    .select()
    .where({ code: In([...goodCode]) })
    .getMany()

  // 3.5. 一个从查询后的数据中根据索引获取 credit_amount 的函数
  function getVal(data: any[], index: string) {
    return data.filter((item) => item.code === index)[0]["sum_debit"]
  }

  // 4. 将数据填充到Sheet中
  Sht?.eachRow((row) => {
    const index = row.getCell(indexCol).value
    if (typeof index === "string") {
      let credit_amount = ""
      if (index.indexOf(",") !== -1) {
        const indexs = index.split(",")
        credit_amount = indexs.reduce(
          (p, c) => getVal(result, p) + getVal(result, c)
        )
      } else {
        credit_amount = getVal(result, index)
      }
      if (credit_amount) row.getCell(fillCol).value = credit_amount
    }
  })

  // 5. 将数据保存到指定路径
  await RyExcel.saveFile(saveFilePath)
}

export { fillTemplateByRecord }
